import * as XLSX from 'xlsx'
import dayjs from 'dayjs'

function jsonToExcel(json, header, filename, sheetName = 'Sheet1') {
  return new Promise((resolve, reject) => {
    try {
      const workBook = XLSX.utils.book_new()
      const workSheet = XLSX.utils.json_to_sheet(json, { header })
      XLSX.utils.book_append_sheet(workBook, workSheet, sheetName)
      resolve(XLSX.writeFileXLSX(workBook, filename))
    } catch (e) {
      reject(e)
    }
  })
}

function csvExcelToJson(file, encoding) {
  return new Promise((resolve, reject) => {
    try {
      const reader = new FileReader()
      let options = {}
      if (file.type === 'text/csv') {
        reader.readAsText(file, encoding)
        options = { type: 'binary', raw: true, codepage: 936 }
      } else {
        reader.readAsArrayBuffer(file)
        options = { type: 'binary' }
      }
      reader.onload = e => {
        try {
          const workBook = XLSX.read(e.target.result, options)
          const jsonData = {}
          if (workBook.SheetNames && workBook.SheetNames.length > 0) {
            for (const sheetName of workBook.SheetNames) {
              jsonData[sheetName] = XLSX.utils.sheet_to_json(workBook.Sheets[sheetName])
            }
          }
          resolve(jsonData)
        } catch (e) {
          reject(e)
        }
      }
    } catch (e) {
      reject(e)
    }
  })
}

const formatTimestamp = (timestamp, template = 'YYYY/MM/DD HH:mm:ss') => {
  return dayjs(parseInt(timestamp)).format(template)
}

const copyText = (function () {
  if (navigator.clipboard) {
    return text => {
      navigator.clipboard.writeText(text)
    }
  } else {
    return text => {
      const input = document.createElement('input')
      input.setAttribute('value', text)
      document.body.appendChild(input)
      input.select()
      document.execCommand('copy')
      document.body.removeChild(input)
    }
  }
})()

export default {
  formatTimestamp,
  jsonToExcel,
  csvExcelToJson,
  copyText
}
